package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.mapper.MenuMapper;
import com.itheima.mapper.PermissionMapper;
import com.itheima.mapper.RoleMapper;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.*;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.*;

@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private JedisPool jedisPool;

    @Override
    public User findByUsername(String username) {
        User user = userMapper.findByUsername(username);
        if(user == null) return null;       //如果用户不存在 返回空
        //通过userid 找到 roles
        Set<Role> roles = roleMapper.findByUserId(user.getId());
        for (Role role : roles) {
            //通过roleId找到权限
            Set<Permission> permissions = permissionMapper.findByRoleId(role.getId());
            role.setPermissions(permissions);
        }
        user.setRoles(roles);       //把包含权限集合的roles封装禁user
        return user;
    }

    @Override
    public LinkedHashSet<Menu> getMenuListByUsername(String username) {
        User user = userMapper.findByUsername(username);
        if(user == null) return null;       //如果用户不存在 返回空
        //通过userid 找到 roles
        Set<Role> roles = roleMapper.findByUserId(user.getId());
        LinkedHashSet<Menu> menus = new LinkedHashSet<>();
        for (Role role : roles) {
            //通过roleId找到一级menu
            LinkedHashSet<Menu> rolePMenus = menuMapper.findPMenusByRoleId(role.getId());
            for (Menu pMenu : rolePMenus) {
                Map map = new HashMap();
                map.put("pid",pMenu.getId());
                map.put("roleId",role.getId());
                List<Menu> cMenus = menuMapper.findCMenusByPidAndRid(map);
                pMenu.setChildren(cMenus);
            }
            //附加菜单内容
            menus.addAll(rolePMenus);
        }
        return menus;
    }

    @Override
    public User findByTelephone(String telephone) {
        User user = userMapper.findByTelephone(telephone);
        if(user == null) return null;       //如果用户不存在 返回空
        //通过userid 找到 roles
        Set<Role> roles = roleMapper.findByUserId(user.getId());
        for (Role role : roles) {
            //通过roleId找到权限
            Set<Permission> permissions = permissionMapper.findByRoleId(role.getId());
            role.setPermissions(permissions);
        }
        user.setRoles(roles);       //把包含权限集合的roles封装禁user
        return user;
    }

    //修改密码
    @Override
    public void changPwd(String telephone, String password) {
        Map map = new HashMap<>();
        map.put("telephone",telephone);
        map.put("password",password);
        userMapper.changPwd(map);
    }

    @Override
    public String getAvatarByUsername(String username) {
        return userMapper.getAvatarByUsername(username);
    }

    @Override
    public void chgAvatarByUsername(String username, String avatar) {
        Map map = new HashMap<>();
        map.put("username",username);
        map.put("avatar",avatar);
        userMapper.chgAvatarByUsername(map);
        //添加数据库方 图片名
        if (avatar != null) {
            Jedis resource = jedisPool.getResource();
            resource.sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, avatar);
            //释放资源
            resource.close();
        }
    }

    /**
     * 获取全体用户头像的名称
     * @return
     */
    @Override
    public List<String> findAllImg() {
        return userMapper.findAllImg();
    }

    /**
     * 分页遍历/模糊查询用户信息
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());//开始分页
        Page<User> page=userMapper.findPage(queryPageBean.getQueryString());//查询数据库
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 新增用户(包含其关联的角色)
     * @param roleIds
     * @param user
     */
    @Override
    public void add(Integer[] roleIds, User user) {
        userMapper.add(user);//添加用户
        Integer user_id=user.getId();//用户id
        if (roleIds != null & roleIds.length > 0) {
            for (Integer id : roleIds) {
                Map<String, Integer> map = new HashMap<>();
                map.put("user_id",user_id);
                map.put("role_id",id);
                userMapper.setUserAndRole(map);
            }
        }
    }

    /**
     * 根据id查询用户信息
     * @param id
     * @return
     */
    @Override
    public User findByUserId(Integer id) {
        return userMapper.findByUserId(id);
    }

    /**
     * 根据用户id查询其对应的角色
     * @param id
     * @return
     */
    @Override
    public List<Role> findRoleByUserId(Integer id) {
        return userMapper.findRoleByUserId(id);
    }

    /**
     * 编辑用户信息
     * @param roleIds
     * @param user
     */
    @Override
    public void edit(Integer[] roleIds, User user) {
        //获取当前用户id
        Integer userId = user.getId();
        //删除原有用户和角色的关联关系
        userMapper.deleteUserAndRoleById(userId);
        //新增现有用户和角色的关联关系
        Map<String,Integer> map=new HashMap();;
        if (roleIds!=null&&roleIds.length>0){
            for (Integer roleId : roleIds) {
                map.put("user_id",userId);
                map.put("role_id",roleId);
                userMapper.setUserAndRole(map);
            }
        }
        //修改用户信息
        userMapper.edit(user);
    }

    /**
     * 根据id删除指定用户
     * @param id
     */
    @Override
    public void delete(Integer id) {
        //首先取消用户和角色的关联关系
        userMapper.deleteUserAndRoleById(id);
        //删除响应用户
        userMapper.deleteById(id);
    }

    /**
     * 修改指定用户状态
     * @param id
     * @param station
     * @return
     */
    @Override
    public Result updateStation(Integer id, String station) {
        try{
            String sid=String.valueOf(id);
            Map map=new HashMap();
            map.put("id",sid);
            map.put("station",station);
            userMapper.updateStation(map);
            return new Result(true,"修改状态成功");
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"修改状态失败");
        }
    }
}
